#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 将单方法的类转换为函数
问题: 你有一个除 __init__() 方法外只定义了一个方法的类。为了简化代码，你想将它转换成一个函数。
提示 : 
"""

from urllib.request import urlopen


class UrlTemplate:
    def __init__(self, template):
        self.template = template

    def open(self, **kwargs):
        return urlopen(self.template.format_map(kwargs))

def recipe1():
    yahoo = UrlTemplate('http://finance.yahoo.com/d/quotes.csv?s={names}&f={fields}')
    for line in yahoo.open(names='IBM,AAPL,FB', fields='sl1c1v'):
        print(line.decode('utf-8'))

def recipe2():
    yahoo = urltemplate('http://finance.yahoo.com/d/quotes.csv?s={names}&f={fields}')
    for line in yahoo(names='IBM,AAPL,FB', fields='sl1c1v'):
        print(line.decode('utf-8'))

def urltemplate(template):
    '''使用闭包来将单个方法的类转换成函数'''
    def opener(**kwargs):
        return urlopen(template.format_map(kwargs))
    return opener

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()

if __name__ == '__main__':
    main()    